package com.yunduo.handler.exceptionhandler;

import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.HttpRequestMethodNotSupportedException;
/**
 * 统一异常处理
 * 异常处理顺序
 *     自定义异常
 *     特定异常
 *     全局异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //全局异常处理
    @ExceptionHandler(Exception.class)
    public CommonReturn globalError(Exception e) {
        e.printStackTrace();
        return CommonReturn.ERROR(ResultCode.UNDEFINE);
    }

    // 非法请求
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonReturn requestError(HttpRequestMethodNotSupportedException e){
        e.printStackTrace();
        return CommonReturn.ERROR(ResultCode.REQUEST_UNDEFINE);
    }

    // 参数错误 使用@Valid参数校验
    @ExceptionHandler(BindException.class)
    public CommonReturn nullError(BindException e){
        e.printStackTrace();
        String errorMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return CommonReturn.ERROR(ResultCode.ERROR).setMessage(errorMessage);
    }

    //权限异常
    @ExceptionHandler(UnauthorizedException.class)
    public CommonReturn error(UnauthorizedException e){
        return CommonReturn.ERROR(ResultCode.ERROR).setMessage("权限不足");
    }

    //自定义异常
    @ExceptionHandler(OperationException.class)
    public CommonReturn error(OperationException e){
        return CommonReturn.ERROR(ResultCode.ERROR).setMessage(e.getMsg());
    }

    @ExceptionHandler(RedisSystemException.class)
    public CommonReturn redisError(RedisSystemException e){
        return CommonReturn.ERROR(ResultCode.ERROR).setMessage("网络波动");
    }
}
